<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="单号" prop="oddNumber">
        <el-input
          v-model="queryParams.oddNumber"
          placeholder="请输入单号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="小屋" prop="lovehouseId">
        <el-cascader
          v-model="queryParams.lovehouseId"
          :options="schoolList"
          :props="{
            value: 'value',
            label: 'label',
            children: 'children',
            emitPath: false,
          }"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
        >
          <el-option
            v-for="dict in donation_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
     <!--  <el-form-item label="入库时间" prop="storageTime">
        <el-date-picker
          clearable
          v-model="queryParams.storageTime"
          type="date"
          value-format="YYYY-MM-DD"
          placeholder="请选择入库时间"
        >
        </el-date-picker>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['manage:donation:add']"
          >新增</el-button
        >
      </el-col>

      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="donationList">
      <el-table-column
        label="序号"
        align="center"
        prop="id"
        type="index"
        width="55px"
      />
      <el-table-column label="单号" align="center" prop="oddNumber" />
      <el-table-column label="捐赠用户" align="center" prop="donorName" />
      <el-table-column label="物品种类" align="center" prop="categoryId">
        <template #default="scope">
          {{ getDonationTypeName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column
        label="物品主图"
        align="center"
        prop="images"
        width="100"
      >
        <template #default="scope">
          <image-preview :src="scope.row.images" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <el-tag :type="getStatusType(scope.row.status)" effect="dark">
            {{ getDictLabel(donation_status, scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="申请时间"
        align="center"
        prop="createTime"
        width="180"
      >
        <template #default="scope">
          <span>{{
            parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{m}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleLookDetails(scope.row.id)"
            v-hasPermi="['manage:donation:query']"
            >查看详情</el-button
          >
          <el-button
            link
            type="primary"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:donation:edit']"
            >修改</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改捐赠物品对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form
        ref="donationRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="单号" prop="oddNumber">
          <el-input
            v-model="form.oddNumber"
            placeholder="由系统自动生成"
            disabled
          />
        </el-form-item>
        <el-form-item label="物品图片" prop="images">
          <image-upload v-model="form.images" />
        </el-form-item>
        <el-form-item label="类型" prop="category_id">
          <el-select v-model="form.categoryId" placeholder="请选择">
            <el-option
              v-for="item in donationTypeList"
              :key="item.id"
              :label="item.typeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="小屋" prop="lovehouseId">
        <el-cascader
          v-model="form.lovehouseId"
          :options="schoolList"
          :props="{
            value: 'value',
            label: 'label',
            children: 'children',
            emitPath: false,
          }"
          clearable
        ></el-cascader>
      </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in donation_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物品描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看详情对话框 -->
    <donation-detail-dialog
      ref="donationDetailRef"
      :schools="schools"
      :donation-visible="false"
      :donation-detail="{}"
      @handle-close-donation="getList"
      @refresh="getList"
    />
  </div>
</template>

<script setup name="Donation">
import {
  listDonation,
  getDonation,
  delDonation,
  addDonation,
  updateDonation,
} from "@/api/manage/donation";
import { listDonationType } from "@/api/manage/donationType";
import { getUser } from "@/api/manage/user";
import { voListSchool } from "@/api/manage/school";
import { listLovehouseManage } from "@/api/manage/lovehouseManage";
import { get } from "@vueuse/core";
import DonationDetailDialog from './components/DonationDetailDialog.vue'
import { listSchool } from "../../../api/manage/school";

const { proxy } = getCurrentInstance();
const { donation_status } = proxy.useDict("donation_status");
const { reject_reason } = proxy.useDict("reject_reason");

/** 根据状态设置标签类型 */
const getStatusType = (status) => {
  if (status === 0) {
    return ""; // 对应蓝色
  } else if (status === 1) {
    return "danger"; // 对应红色
  } else if ([3, 4].includes(status)) {
    return "success"; // 对应绿色
  } else if (status === 2) {
    return "warning"; // 对应黄色
  } else if (status === 5) {
    return "info"; // 对应灰色
  }
  // 默认返回空字符串，避免无效状态影响样式
  return "";
};

/** 根据字典选项获取标签文本 */
const getDictLabel = (options, value) => {
  for (let i = 0; i < options.length; i++) {
    if (options[i].value == value) {
      return options[i].label;
    }
  }
};

const donationList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const schools  = ref([]);//学校集合-用于传递给捐赠物详情组件-再传递给用户详情组件

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    oddNumber: null,
    donorId: null,
    receiverId: null,
    categoryId: null,
    status: null,
    storageTime: null,
  },
  rules: {
    donorId: [{ required: true, message: "捐赠人ID不能为空", trigger: "blur" }],
    categoryId: [{ required: true, message: "类型不能为空", trigger: "blur" }],
    images: [{ required: true, message: "物品图片不能为空", trigger: "blur" }],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
    description: [
      { required: true, message: "物品描述不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);


/**获取学校级联列表 */
const schoolList = ref([]);
function getSchoolsData() {//获取学校集合
  listSchool().then((response) => {
    schools.value = response.rows;
  });
}
function getSchoolList() {
  voListSchool().then((response) => {
    const filteredRows = response.rows.filter(
      (item) =>
        Array.isArray(item.lovehouseList) && item.lovehouseList.length > 0
    );
    filteredRows.forEach((item) => {
      schoolList.value.push({
        value: item.id,
        label: item.schoolName,
        children: item.lovehouseList.map((lovehouse) => {
          return {
            value: lovehouse.id,
            label: lovehouse.houseName,
          };
        }),
      });
    });
  });
}

/**获取种类列表 */
const donationTypeList = ref([]);
function getDonationTypeList() {
  listDonationType().then((response) => {
    donationTypeList.value = response.rows;
  });
}

/**根据id查询种类名称 */
function getDonationTypeName(id) {
  for (let i = 0; i < donationTypeList.value.length; i++) {
    if (donationTypeList.value[i].id == id) {
      return donationTypeList.value[i].typeName;
    }
  }
}

/** 查询捐赠物品列表 */
function getList() {
  loading.value = true;
  listDonation(queryParams.value).then((response) => {
    donationList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    oddNumber: null,
    donorId: null,
    receiverId: null,
    categoryId: null,
    images: null,
    status: null,
    description: null,
    cancelReason: null,
    storageTime: null,
    createTime: null,
    updateTime: null,
    createBy: null,
    updateBy: null,
    remark: null,
  };
  proxy.resetForm("donationRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加捐赠物品";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getDonation(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改捐赠物品";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["donationRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateDonation(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDonation(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除捐赠物品编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delDonation(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "manage/donation/export",
    {
      ...queryParams.value,
    },
    `donation_${new Date().getTime()}.xlsx`
  );
}

const donationDetailRef = ref(null);

/**
 * 查看详情按钮操作
 */
function handleLookDetails(id) {
  donationDetailRef.value?.handleLookDetails(id);
}

getSchoolList();
getDonationTypeList();
getList();
getSchoolsData();
</script>
<style scoped>
.red-status {
  color: rgb(241, 42, 16);
}
.blue-status {
  color: rgb(38, 129, 234);
}
.green-status {
  color: rgb(0, 204, 0);
}
</style>